import process from 'process'
import {isEmpty} from '../utils'
import fs from 'fs'
import {BaseCommand} from './base'
import os from 'os'

export const FILE_COMMAND_PATH = 'PATH'
export const FILE_COMMAND_ENV = 'ENV'

export class FileCommand extends BaseCommand {
    private readonly command: string
    private readonly message: string

    constructor(command: string, message: string) {
        super()
        if (isEmpty(command)) {
            throw new Error("missing 'command'")
        }
        this.command = command
        this.message = message
    }

    toString(): string {
        return this.command + this.escapeMessage(this.message)
    }

    escapedMessage(): string {
        return this.escapeMessage(this.message)
    }
}

export function callFileCommand(commandName: string, message: string): void {
    const commandFilePath = process.env[`FLOW_${commandName}`] as string
    if (isEmpty(commandFilePath)) {
        throw new Error(
            `can not find env variable for file command ${commandName}`
        )
    }

    if (!fs.existsSync(commandFilePath)) {
        throw new Error(`can not find command file ${commandFilePath}`)
    }

    const fileCommand = new FileCommand(commandName, message)
    fs.appendFileSync(commandFilePath, fileCommand.escapedMessage() + os.EOL, {
        encoding: 'utf8'
    })
}
